package thread;

class Counter{
    volatile  public int count = 0;//volatile 不保证原子性
    synchronized public void increase(){
        count++;
    }

//    public static void func(){
//        synchronized (Counter.class){
//
//        }
}
public class demo15 {
    private static  Counter counter = new Counter();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() ->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        //必须要在t1,t2都执行完了之后，再打印count
        //否则，t1,t2,main都是并发执行的关系，导致t1，t2还没执行完，就先执行了下面的打印操作
        //在main中打印两个线程执行自增完成之后，得到的count结果
        System.out.println(counter.count);
    }
}
